<template>
  <div class="activity-detail">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>
    
    <!-- 活动详情 -->
    <div v-else-if="activity" class="detail-container">
      <!-- 返回按钮 -->
      <div class="back-button">
        <el-button @click="goBack" :icon="ArrowLeft">
          返回列表
        </el-button>
      </div>
      
      <!-- 活动头部信息 -->
      <el-card class="header-card">
        <div class="activity-header">
          <div class="header-content">
            <h1 class="activity-title">{{ activity.title }}</h1>
            <div class="activity-tags">
              <el-tag :type="getActivityStatus(activity).type" size="large">
                {{ getActivityStatus(activity).text }}
              </el-tag>
              <el-tag type="info" size="large">
                {{ getActivityTypeText(activity.type) }}
              </el-tag>
              <el-tag v-if="activity.isHot" type="danger" size="large">
                <el-icon><Star /></el-icon>
                热门活动
              </el-tag>
            </div>
            <p class="activity-description">{{ activity.description }}</p>
          </div>
          <div class="header-actions">
            <el-button 
              type="primary" 
              size="large"
              @click="handleRegister"
              :disabled="!canRegister"
              :loading="registering"
            >
              {{ registerButtonText }}
            </el-button>
            <el-button 
              size="large"
              @click="handleShare"
              :icon="Share"
            >
              分享
            </el-button>
          </div>
        </div>
      </el-card>
      
      <el-row :gutter="20">
        <!-- 左侧主要内容 -->
        <el-col :xs="24" :lg="16">
          <!-- 活动详细信息 -->
          <el-card class="info-card">
            <template #header>
              <div class="card-header">
                <el-icon><InfoFilled /></el-icon>
                <span>活动信息</span>
              </div>
            </template>
            
            <div class="info-grid">
              <div class="info-item">
                <div class="info-label">
                  <el-icon><Clock /></el-icon>
                  开始时间
                </div>
                <div class="info-value">{{ formatDate(activity.startTime) }}</div>
              </div>
              
              <div class="info-item">
                <div class="info-label">
                  <el-icon><Clock /></el-icon>
                  结束时间
                </div>
                <div class="info-value">{{ formatDate(activity.endTime) }}</div>
              </div>
              
              <div class="info-item">
                <div class="info-label">
                  <el-icon><Location /></el-icon>
                  活动地点
                </div>
                <div class="info-value">{{ activity.location }}</div>
              </div>
              
              <div class="info-item">
                <div class="info-label">
                  <el-icon><Calendar /></el-icon>
                  报名截止
                </div>
                <div class="info-value">{{ formatDate(activity.registrationDeadline) }}</div>
              </div>
              
              <div class="info-item">
                <div class="info-label">
                  <el-icon><User /></el-icon>
                  参与人数
                </div>
                <div class="info-value">
                  {{ activity.currentParticipants || 0 }}/{{ activity.maxParticipants || '不限' }}
                </div>
              </div>
              
              <div class="info-item">
                <div class="info-label">
                  <el-icon><UserFilled /></el-icon>
                  组织者
                </div>
                <div class="info-value">{{ activity.organizer?.name }}</div>
              </div>
            </div>
          </el-card>
          
          <!-- 活动详细描述 -->
          <el-card class="content-card">
            <template #header>
              <div class="card-header">
                <el-icon><Document /></el-icon>
                <span>活动详情</span>
              </div>
            </template>
            
            <div class="activity-content" v-html="activity.content || '暂无详细描述'">
            </div>
          </el-card>
          
          <!-- 报名规则 -->
          <el-card v-if="activity.registrationRules" class="rules-card">
            <template #header>
              <div class="card-header">
                <el-icon><Warning /></el-icon>
                <span>报名规则</span>
              </div>
            </template>
            
            <div class="rules-content">
              <div v-if="activity.registrationRules.conditions?.length > 0" class="rule-section">
                <h4>报名条件：</h4>
                <ul>
                  <li v-for="condition in activity.registrationRules.conditions" :key="condition">
                    {{ condition }}
                  </li>
                </ul>
              </div>
              
              <div v-if="activity.registrationRules.requirements?.length > 0" class="rule-section">
                <h4>注意事项：</h4>
                <ul>
                  <li v-for="requirement in activity.registrationRules.requirements" :key="requirement">
                    {{ requirement }}
                  </li>
                </ul>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 右侧边栏 -->
        <el-col :xs="24" :lg="8">
          <!-- 组织者信息 -->
          <el-card class="organizer-card">
            <template #header>
              <div class="card-header">
                <el-icon><UserFilled /></el-icon>
                <span>组织者</span>
              </div>
            </template>
            
            <div class="organizer-info">
              <div class="organizer-avatar">
                <el-avatar :size="60" :src="activity.organizer?.avatar">
                  {{ activity.organizer?.name?.charAt(0) }}
                </el-avatar>
              </div>
              <div class="organizer-details">
                <h4>{{ activity.organizer?.name }}</h4>
                <p v-if="activity.organizer?.organization">{{ activity.organizer?.organization }}</p>
                <p v-if="activity.organizer?.contact">{{ activity.organizer?.contact }}</p>
              </div>
            </div>
            
            <div class="organizer-actions">
              <el-button type="primary" @click="contactOrganizer" block>
                <el-icon><ChatDotRound /></el-icon>
                联系组织者
              </el-button>
            </div>
          </el-card>
          
          <!-- 报名统计 -->
          <el-card class="stats-card">
            <template #header>
              <div class="card-header">
                <el-icon><DataAnalysis /></el-icon>
                <span>报名统计</span>
              </div>
            </template>
            
            <div class="stats-content">
              <div class="stat-item">
                <div class="stat-number">{{ activity.currentParticipants || 0 }}</div>
                <div class="stat-label">已报名</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ activity.maxParticipants || '∞' }}</div>
                <div class="stat-label">最大人数</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ remainingDays }}</div>
                <div class="stat-label">剩余天数</div>
              </div>
            </div>
            
            <!-- 进度条 -->
            <div v-if="activity.maxParticipants" class="progress-section">
              <div class="progress-label">
                报名进度：{{ Math.round((activity.currentParticipants || 0) / activity.maxParticipants * 100) }}%
              </div>
              <el-progress 
                :percentage="Math.round((activity.currentParticipants || 0) / activity.maxParticipants * 100)"
                :color="getProgressColor((activity.currentParticipants || 0) / activity.maxParticipants)"
              />
            </div>
          </el-card>
          
          <!-- 相关活动 -->
          <el-card v-if="relatedActivities.length > 0" class="related-card">
            <template #header>
              <div class="card-header">
                <el-icon><Connection /></el-icon>
                <span>相关活动</span>
              </div>
            </template>
            
            <div class="related-activities">
              <div 
                v-for="related in relatedActivities" 
                :key="related.id"
                class="related-item"
                @click="goToActivity(related.id)"
              >
                <div class="related-title">{{ related.title }}</div>
                <div class="related-meta">
                  <span class="related-time">{{ formatDate(related.startTime, 'MM-DD') }}</span>
                  <el-tag size="small" :type="getActivityStatus(related).type">
                    {{ getActivityStatus(related).text }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-result
        icon="error"
        title="活动不存在"
        sub-title="您访问的活动可能已被删除或不存在"
      >
        <template #extra>
          <el-button type="primary" @click="goBack">
            返回列表
          </el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { formatDate, getActivityStatus } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import {
  ArrowLeft,
  Star,
  Share,
  InfoFilled,
  Clock,
  Location,
  Calendar,
  User,
  UserFilled,
  Document,
  Warning,
  ChatDotRound,
  DataAnalysis,
  Connection
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const loading = ref(true)
const registering = ref(false)
const activity = ref(null)
const relatedActivities = ref([])
const isRegistered = ref(false)

const activityId = computed(() => route.params.id)

const getActivityTypeText = (type) => {
  const typeMap = {
    ACADEMIC: '学术类',
    CULTURAL: '文体类',
    VOLUNTEER: '志愿服务',
    CLUB: '社团活动',
    OTHER: '其他'
  }
  return typeMap[type] || type
}

const canRegister = computed(() => {
  if (!activity.value || isRegistered.value) return false
  const status = getActivityStatus(activity.value)
  return status.status === 'registration'
})

const registerButtonText = computed(() => {
  if (isRegistered.value) return '已报名'
  if (!activity.value) return '加载中...'
  
  const status = getActivityStatus(activity.value)
  switch (status.status) {
    case 'registration':
      return '立即报名'
    case 'waiting':
      return '报名已截止'
    case 'ongoing':
      return '进行中'
    case 'ended':
      return '已结束'
    default:
      return '查看详情'
  }
})

const remainingDays = computed(() => {
  if (!activity.value?.registrationDeadline) return '-'
  const deadline = new Date(activity.value.registrationDeadline)
  const now = new Date()
  const diff = deadline - now
  const days = Math.ceil(diff / (1000 * 60 * 60 * 24))
  return days > 0 ? days : 0
})

const getProgressColor = (percentage) => {
  if (percentage < 0.5) return '#67c23a'
  if (percentage < 0.8) return '#e6a23c'
  return '#f56c6c'
}

const loadActivity = async () => {
  try {
    loading.value = true
    
    const response = await api.get(`/activities/${activityId.value}`)
    activity.value = response.data.data
    
    // 检查是否已报名
    await checkRegistrationStatus()
    
    // 加载相关活动
    await loadRelatedActivities()
    
  } catch (error) {
    console.error('加载活动详情失败:', error)
    ElMessage.error('加载活动详情失败')
  } finally {
    loading.value = false
  }
}

const checkRegistrationStatus = async () => {
  try {
    const response = await api.get('/registrations/my-activities')
    const registeredIds = response.data.data?.map(item => item.activityId) || []
    isRegistered.value = registeredIds.includes(parseInt(activityId.value))
  } catch (error) {
    console.error('检查报名状态失败:', error)
  }
}

const loadRelatedActivities = async () => {
  try {
    const response = await api.get('/activities', {
      params: {
        type: activity.value?.type,
        exclude: activityId.value,
        size: 5
      }
    })
    relatedActivities.value = response.data.data?.data || []
  } catch (error) {
    console.error('加载相关活动失败:', error)
  }
}

const handleRegister = async () => {
  if (!canRegister.value) return
  
  try {
    await ElMessageBox.confirm(
      `确定要报名参加「${activity.value.title}」吗？`,
      '确认报名',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    registering.value = true
    
    await api.post('/registrations', {
      activityId: parseInt(activityId.value)
    })
    
    ElMessage.success('报名成功，请等待审核')
    isRegistered.value = true
    
    // 刷新活动信息
    await loadActivity()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('报名失败:', error)
      ElMessage.error(error.message || '报名失败')
    }
  } finally {
    registering.value = false
  }
}

const handleShare = async () => {
  try {
    if (navigator.share) {
      await navigator.share({
        title: activity.value.title,
        text: activity.value.description,
        url: window.location.href
      })
    } else {
      // 复制链接到剪贴板
      await navigator.clipboard.writeText(window.location.href)
      ElMessage.success('链接已复制到剪贴板')
    }
  } catch (error) {
    console.error('分享失败:', error)
    ElMessage.error('分享失败')
  }
}

const contactOrganizer = () => {
  ElMessage.info('联系组织者功能开发中...')
}

const goBack = () => {
  router.go(-1)
}

const goToActivity = (id) => {
  router.push(`/student/activities/${id}`)
}

onMounted(() => {
  loadActivity()
})
</script>

<style scoped>
.activity-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.loading-container,
.error-container {
  padding: 60px 20px;
  text-align: center;
}

.back-button {
  margin-bottom: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.header-content {
  flex: 1;
}

.activity-title {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  margin: 0 0 16px 0;
  line-height: 1.3;
}

.activity-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.activity-description {
  font-size: 16px;
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

.header-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 160px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.info-card,
.content-card,
.rules-card {
  margin-bottom: 20px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.info-value {
  font-size: 16px;
  color: #303133;
  font-weight: 600;
}

.activity-content {
  font-size: 16px;
  line-height: 1.8;
  color: #606266;
}

.rules-content {
  color: #606266;
}

.rule-section {
  margin-bottom: 20px;
}

.rule-section h4 {
  color: #303133;
  margin: 0 0 12px 0;
  font-weight: 600;
}

.rule-section ul {
  margin: 0;
  padding-left: 20px;
}

.rule-section li {
  margin-bottom: 8px;
  line-height: 1.6;
}

.organizer-card,
.stats-card,
.related-card {
  margin-bottom: 20px;
}

.organizer-info {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.organizer-details h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-weight: 600;
}

.organizer-details p {
  margin: 0 0 4px 0;
  color: #909399;
  font-size: 14px;
}

.stats-content {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.progress-section {
  margin-top: 20px;
}

.progress-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.related-activities {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.related-item {
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.related-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.related-title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  font-size: 14px;
  line-height: 1.4;
}

.related-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.related-time {
  font-size: 12px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .activity-detail {
    padding: 10px;
  }
  
  .activity-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    flex-direction: row;
    min-width: auto;
  }
  
  .activity-title {
    font-size: 24px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .stats-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .organizer-info {
    flex-direction: column;
    text-align: center;
  }
}
</style>